package com.klikmee.sms.core.base.postman;

import java.text.MessageFormat;

import org.apache.log4j.Logger;

import com.klikmee.sms.cef.services.ws.ServiceRequestMessage;
import com.klikmee.sms.core.base.EventManager;
import com.klikmee.sms.core.base.util.CoreUtilities;
import com.klikmee.sms.core.commons.events.AppEvent;
import com.klikmee.sms.core.commons.queues.QueueItem;
import com.klikmee.sms.core.model.IncomingMessage;

public class IncomingMessageQueueItemProcessorImpl extends ItemProcessorBase<IncomingMessage> {
	
	// logger instance
	private Logger logger = Logger.getLogger( IncomingMessageQueueItemProcessorImpl.class );
	
	@Override
	public boolean process(QueueItem<IncomingMessage> item) {
		// extract payload and try to delivery to service
		IncomingMessage incomingMessage = item.getPayload();
		String endpointURL = incomingMessage.getService().getEndpoint();
		
		overrideEndpointAddress( endpointURL );

		// deliver message to service
		ServiceRequestMessage serviceRequestMessage = this.createServiceRequestMessage( incomingMessage );
		
		try {
			serviceProxy.onRequestMessage( serviceRequestMessage );
			logger.info( MessageFormat.format( "Delivered message with id [{0}] to service name = [{1}]", incomingMessage.getId(), incomingMessage.getService().getName() ) );
			
			// announse message delivered event
			AppEvent event = new AppEvent( EventManager.INCOMING_MESSAGE_DELIVERED_TO_SERVICE, incomingMessage );
			this.dispatcher.dispatch( event );
			// if everything OK, return true
			return true;
		}
		catch (Exception e) {
			logger.fatal( MessageFormat.format( "Failed to deliver [{0}] to service", incomingMessage), e );
			return false;
		}
	}
	
	public ServiceRequestMessage createServiceRequestMessage(IncomingMessage incomingMessage) {
		ServiceRequestMessage message = new ServiceRequestMessage();
		message.setCoreId( incomingMessage.getId() );
		message.setFromNumber( incomingMessage.getFromNumber() );
		message.setMessageText( incomingMessage.getMessage() );
		message.setTimeReceived( CoreUtilities.convertToXMLGregorianCalendar( incomingMessage.getOurIncomingTime() ) );
		message.setToNumber( incomingMessage.getToNumber() );

		return message;
	}

}
